﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.WebControls;

namespace PeoplePickerPlus.Entities
{
    public class EntityInfo
    {
        public string Login;
        public int ID;
        public string Display;
        public string Email;
        public bool IsSPGroup;
        public string PrincipalType;
        public string ParentUrl;
        public string ProviderName;

        public EntityInfo()
        {
            ProviderName = "Unknown";
        }

        public EntityInfo(SPPrincipalInfo principal)
        {
            ID = principal.PrincipalId;
            Login = principal.LoginName;
            Display = principal.DisplayName;
            Email = principal.Email;
            IsSPGroup = principal.IsSharePointGroup;
            PrincipalType = principal.PrincipalType.ToString();
            
            //if (principal.PrincipalType == SPPrincipalType.SecurityGroup)
            {
                Display = Regex.Replace(Display, ".*\\\\(.*)", "$1", RegexOptions.None);
            }

            if (IsSPGroup)
            {
                ParentUrl = GetGroupInfo(ID);
            }
        }

        public EntityInfo(SPListItem principal)
        {
            ID = principal.ID;
            Login = Convert.ToString(principal["Name"]);
            Display = Convert.ToString(principal["Title"]);
            Email = Convert.ToString(principal["EMail"]);

            string contentType = Convert.ToString(principal["ContentType"]);

            SPPrincipalType principalType = GetPrincipalTypeFromContentType(contentType);

            PrincipalType = principalType.ToString();
            IsSPGroup = principalType == SPPrincipalType.SharePointGroup;
        }

        public EntityInfo(PickerEntity entity)
        {
            ID = -1;
            Login = entity.Key;
            Display = entity.DisplayText;

            if (!string.IsNullOrEmpty(Display))
            {
                Display = Regex.Replace(Display, ".*\\\\(.*)", "$1", RegexOptions.None);
            }

            SPPrincipalType principalType = GetPrincipalTypeFromEntityType(entity.EntityType);
            PrincipalType = principalType.ToString();
            IsSPGroup = principalType == SPPrincipalType.SharePointGroup;

            if (entity.EntityData != null && entity.EntityData.ContainsKey("Email"))
            {
                Email = Convert.ToString(entity.EntityData["Email"]);

                if (string.Equals(entity.EntityType, "User", StringComparison.OrdinalIgnoreCase)
                    && string.Equals(entity.ProviderName, "Forms", StringComparison.OrdinalIgnoreCase))
                {
                    //update display of forms users
                    Regex re = new Regex("(.*?)<(.*?)>", RegexOptions.None);
                    MatchCollection matches = re.Matches(Email);//Regex.Matches(Email, "(.*?)<(.*?)>", RegexOptions.None);
                    if (matches.Count > 0 && matches[0].Groups.Count > 1)
                    {
                        Display = string.IsNullOrEmpty(matches[0].Groups[1].Value.Trim()) ? Display : matches[0].Groups[1].Value.Trim();
                        Email = matches[0].Groups.Count > 2 ? matches[0].Groups[2].Value.Trim() : Email;
                    }
                }
            }

            ProviderName = entity.ProviderName;
        }

        private static string GetGroupInfo(int id)
        {
            string info = "";
            SPGroup group = SPContext.Current.Site.RootWeb.SiteGroups.GetByID(id);
            if (group != null)
            {
                try
                {
                    if (group.ParentWeb != null)
                    {
                        info = group.ParentWeb.ServerRelativeUrl;
                    }
                }
                finally
                {
                    if (group.ParentWeb != null)
                    {
                        group.ParentWeb.Dispose();
                    }
                }
            }

            return info;
        }

        private static SPPrincipalType GetPrincipalTypeFromContentType(string contentType)
        {
            switch (contentType.ToLower())
            {
                case "person":
                    return SPPrincipalType.User;

                case "domaingroup":
                    return SPPrincipalType.SecurityGroup;

                case "sharepointgroup":
                    return SPPrincipalType.SharePointGroup;
            }

                    return SPPrincipalType.None;
        }

        private static SPPrincipalType GetPrincipalTypeFromEntityType(string entityType)
        {
            switch (entityType.ToLower())
            {
                case "user":
                    return SPPrincipalType.User;

                case "secgroup":
                    return SPPrincipalType.SecurityGroup;

                case "sharepointgroup":
                    return SPPrincipalType.SharePointGroup;
            }

            return SPPrincipalType.None;
        }
    }
}
